package server

import (
	"context"
	"errors"
	jwt "github.com/golangblogs/gojwt"
	"github.com/google/uuid"
	"math/rand"
	"strconv"
	"time"
	"week62/common/model/mysql"
	"week62/common/model/redis"
	"week62/common/proto/user"
	"week62/pkg"
)

func Login(req *user.LoginReq) (*user.LoginResp, error) {
	u := mysql.User{}
	login, err := u.Login(req.Tel, req.Password)
	if err != nil {
		return nil, errors.New("登录失败")
	}

	key := "sms:" + req.Tel
	if redis.RDB.Get(context.Background(), key).Val() != req.Code {
		return nil, errors.New("验证码错误，请重新登录")
	}

	token, err := jwt.NewJWT("week62").CreateToken(jwt.CustomClaims{ID: login.ID})
	if err != nil {
		return nil, errors.New("token生成失败")
	}

	return &user.LoginResp{
		UserId:  int64(login.ID),
		Success: token,
	}, nil
}

func SendSms(req *user.SendSmsReq) (*user.SendSmsResp, error) {
	code := rand.Intn(9000) + 1000

	sms, err := pkg.SendSms(strconv.Itoa(code), req.Tel)
	if err != nil {
		return nil, err
	}
	if *sms.Body.Code != "OK" {
		return nil, errors.New("验证码发送失败")
	}

	key := "sms:" + req.Tel
	err = redis.RDB.Set(context.Background(), key, code, time.Minute*30).Err()
	if err != nil {
		return nil, errors.New("验证码存储redis失败")
	}
	return &user.SendSmsResp{Success: strconv.Itoa(code)}, nil
}

func AddOrder(req *user.AddOrderReq) (*user.AddOrderResp, error) {
	g := mysql.Goods{}
	goods, err := g.Find(req.GoodsId)
	if err != nil {
		return nil, err
	}

	Sn := uuid.New().String()
	o := mysql.Order{
		UserId:     int(req.UserId),
		GoodsId:    int(req.GoodsId),
		OrderSn:    Sn,
		GoodsName:  goods.Name,
		GoodsPrice: goods.Price,
		PayType:    int(req.PayType),
	}
	err = o.Created()
	if err != nil {
		return nil, err
	}
	return &user.AddOrderResp{Success: "下单成功"}, nil
}

func SyncGoods(req *user.SyncGoodsReq) (*user.SyncGoodsResp, error) {
	g := mysql.Goods{}
	finds, err := g.Finds()
	if err != nil {
		return nil, err
	}
	for _, find := range finds {
		err = redis.RDB.LPush(context.Background(), "SyncGood", find).Err()
		if err != nil {
			return nil, errors.New("商品同步失败")
		}
	}

	return &user.SyncGoodsResp{Success: "商品同步成功"}, nil
}
